import React, { useEffect, useState, useRef } from 'react'
import { connect } from 'dva'
import { Row, Col, Input, Select, Button, DatePicker, message } from 'antd'
import request from '../utils/request';
import servicePath from '../config/apiUrl'
import styles from './styles/AddArticle.less'
import marked from 'marked'
import moment from 'moment'
const { Option } = Select
const { TextArea } = Input;



function AddArticle(props) {


  const [articleId, setArticleId] = useState(0)  // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
  const [articleTitle, setArticleTitle] = useState('')   //文章标题
  const [articleContent, setArticleContent] = useState('')  //markdown的编辑内容
  const [markdownContent, setMarkdownContent] = useState('预览内容') //html内容
  const [introducemd, setIntroducemd] = useState()            //简介的markdown内容
  const [introducehtml, setIntroducehtml] = useState('等待编辑') //简介的html内容
  const [showDate, setShowDate] = useState()   //发布日期
  const [updateDate, setUpdateDate] = useState() //修改日志的日期
  const [typeInfo, setTypeInfo] = useState([]) // 文章类别信息
  const [onTap, setOnTap] = useState() //选择的文章类别

  marked.setOptions({
    renderer: marked.Renderer(),
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false,
  });

  const getTypeInfo = () => {
    // axios({
    //   url: servicePath.getTypeInfo,
    //   header: { 'Access-Control-Allow-Origin': '*' },
    //   withCredentials: true
    // }).then(
    //   res => {
    //     console.log("getTypeInfo:",res.data.data)
    //     // if (res.data.data == "没有登录") {
    //     //   localStorage.removeItem('openId')
    //     //   props.history.push('/')
    //     // } else {
    //     //   setTypeInfo(res.data.data)
    //     // }

    //   }
    // )
    request(servicePath.getTypeInfo, {
      method: "get",
      credentials: 'include'//同源跨域都携带cookies/session
    }).then(res => {
      console.log("getTypeInfo--res", res);
      if (res.data.data == "没有登录") {
        localStorage.removeItem('openId')
        props.history.push('/')
      } else {
        setTypeInfo(res.data.data)
      }
    })
  }

  const intervalRef  = useRef();

  const getArticleById = (id) => {
    request(`${servicePath.getArticleById}${id}`, {
      method: "get",
      credentials: 'include'//同源跨域都携带cookies/session
    }).then(
      res => {
        console.log("res.data.data[0]", res.data.data[0])
        //let articleInfo= res.data.data[0]
        setArticleTitle(res.data.data[0].title)
        setArticleContent(res.data.data[0].article_content)
        let html = marked(res.data.data[0].article_content)
        setMarkdownContent(html)
        setIntroducemd(res.data.data[0].introduce)
        let tmpInt = marked(res.data.data[0].introduce)
        setIntroducehtml(tmpInt)
        setShowDate(res.data.data[0].addTime)
        setOnTap(`${res.data.data[0].typeId}`)
        intervalRef.current = res.data.data[0].typeId
        console.log("console.log(typeof onTap)-", onTap, res.data.data[0].typeId, showDate)
        console.log("intervalRef==",intervalRef)

      }
    )
  }

  const handleFoo = () => {
    console.log("handleFoo");
  }

  const changeContent = (e) => {
    setArticleContent(e.target.value)
    let html = marked(e.target.value)
    setMarkdownContent(html)
  }

  const changeIntroduce = (e) => {
    setIntroducemd(e.target.value)
    let html = marked(e.target.value)
    setIntroducehtml(html)
  }


  //选择类别后的便哈
  const selectTypeHandler = (value) => {
    console.log("selectTypeHandler==", value)
    setOnTap(value)
  }
  // 编辑文章保存方法
  const saveArticle = () => {
    if (!onTap) {
      message.error('必须选择文章类别')
      return false
    } else if (!articleTitle) {
      message.error('文章名称不能为空')
      return false
    } else if (!articleContent) {
      message.error('文章内容不能为空')
      return false
    } else if (!introducemd) {
      message.error('简介不能为空')
      return false
    } else if (!showDate) {
      message.error('发布日期不能为空')
      return false
    } else {
      message.success('检验通过')
    }


    let dataProps = {}   //传递到接口的参数
    dataProps.type_id = onTap
    dataProps.title = articleTitle
    dataProps.article_content = articleContent
    dataProps.introduce = introducemd
    let datetext = showDate.replace('-', '/') //把字符串转换成时间戳
    dataProps.addTime = (new Date(datetext).getTime()) / 1000


    if (articleId == 0) {
      console.log('articleId=:' + articleId)
      dataProps.view_count = Math.ceil(Math.random() * 100) + 1000

      request(servicePath.addArticle, {
        method: 'post',
        body: dataProps,
        credentials: 'include'
      }).then(
        res => {
          console.log("res.data----", res.data)
          setArticleId(res.data.insertId)
          if (res.data.code === "0000") {
            message.success('文章保存成功')
          } else {
            message.error('文章保存失败');
          }

        }
      )
    } else {

      console.log('articleId::::' + articleId)

      dataProps.id = articleId

      request(servicePath.updateArticle, {
        method: 'post',
        body: dataProps,
        credentials: 'include'
      }).then(res => {
        console.log("res-update----", res.data)
        if (res.data.code === "0000") {
          message.success('文章更新成功')
        } else {
          message.error('文章更新失败');
        }
      })

    }




  }

  useEffect(() => {
    getTypeInfo()
    //获得文章ID
    let tmpId = props.match.params.id
    if (tmpId) {
      setArticleId(tmpId) //id非0，是更新内容操作
      getArticleById(tmpId) //显示这篇数据
      // setOnTap(222)
      // console.log("onTap",onTap);
      console.log("tm----show", showDate)
    }
  }, [])

  return (
    <div>
      <Row gutter={5}>
        <Col span={18}>
          <Row gutter={10} >
            <Col span={20}>
              <Input
                placeholder="博客标题"
                onChange={e => {
                  setArticleTitle(e.target.value)
                }}
                value={articleTitle}
                size="large" />
            </Col>
            <Col span={4}>
              <Select style={{ width: '100%' }} value={onTap} size="large"
                onChange={selectTypeHandler}>
                {
                  typeInfo.map((item, index) => {
                    return (
                      <Option key={index} value={item.Id}>
                        {item.typeName}
                      </Option>
                    )
                  })
                }
              </Select>
            </Col>
          </Row>
          <br />
          <Row gutter={10} >
            <Col span={12}>
              <TextArea
                className="markdown-content"
                rows={35}
                onChange={changeContent}
                onPressEnter={changeContent}
                placeholder="文章内容"
                value={articleContent}
              />
            </Col>
            <Col span={12}>
              <div
                className={styles["show-html"]}
                dangerouslySetInnerHTML={{ __html: markdownContent }} >
              </div>
            </Col>
          </Row>
        </Col>

        <Col span={6}>
          <Row>
            <Col span={24}>
              <Button size="large">暂存文章</Button>&nbsp;
              <Button type="primary" size="large" onClick={saveArticle}>发布文章</Button>
              <br />
              <TextArea
                rows={4}
                placeholder="文章简介"
                value={introducemd}
                onChange={changeIntroduce}
                onPressEnter={changeIntroduce}
              />
              <br /><br />
              <div className={styles["introduce-html"]}
                dangerouslySetInnerHTML={{ __html: '文章简介：' + introducehtml }} ></div>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <div className="date-select">
                <DatePicker
                  onChange={(date, dateString) => setShowDate(dateString)}
                  placeholder="发布日期"
                  size="large"
                  value={
                    showDate === undefined ? showDate : moment(showDate, 'YYYY-MM-DD')
                  }
                  format="YYYY-MM-DD"
                />
              </div>
            </Col>
          </Row>
        </Col>

      </Row>
    </div>
  )
}


AddArticle.protoTypes = {

}



export default connect()(AddArticle)

